import { nextTick } from 'vue'
import { debounce } from 'lodash-es'

interface IPostMessage {
  el?: string
  messageType?: string
  message: string
  postUrl: string
}
export const useDiyMessageHooks = () => {
  /**
   * 处理接收消息
   */
  const handleGetMessage = () => {
    return new Promise((resolve, reject) => {
      try {
        window.addEventListener('message', async (e: any) => {
          resolve(e)
        })
      } catch (err) {
        reject(err)
      }
    })
  }
  /**
   * 处理发送消息
   */
  const handlePostMessage = (params: IPostMessage) => {
    const { el = '#preview-iframe', messageType = 'diyPreview', message, postUrl } = params
    nextTick(() => {
      const iframe: any = document.querySelector(el)
      iframe.contentWindow.postMessage(
        {
          messageType,
          message
        },
        postUrl
      )
    })
  }
  // 防抖发送
  const debouncePostMessage = debounce((params: IPostMessage) => {
    handlePostMessage(params)
  }, 500)

  return {
    debouncePostMessage,
    handleGetMessage
  }
}
